var itemno = "";
var applyid = "";
var nodeno = "";
var orgcode = "";
var nextnodecode1 = "";
var selectID = "userlist";
var applyno = "";

$(function(){
	applyno = getUrlParam("applyno");
	itemno = getUrlParam("itemno");
	
	if(itemno == '1005'){ // 特殊处理：1005与1002业务一样，by yujunxin 2018/10/21 14:15
		$('#businessForm').load("1002/detail.html");
	} else {
		$('#businessForm').load(itemno + "/detail.html");
	}
	
//	if(itemno == '10001')
//		$('#booklist').hide();
	
	bindApply(applyno);

	
	$('#correction').hide();
	$('#edit').hide();
	$('#change').hide();
	$('.change').hide();
	$('#delete').hide();
	$('#delete').click(function(){
		
		$.confirm({
		    title: '提示!',
		    content: "删除数据就无法恢复，确定删除？",
		    confirmButton: '确定',
		    cancelButton: '取消',
		    confirm: function(){
				var param = {};
				param['applyid'] = applyid;
				param['isdetele'] = "1";
				
				$.ajax({ 
					url: projectPath + 'business/delete.do',
					data: param,
			        dataType: 'json',  
			        contentType:'application/json;charset=UTF-8', 
					success: function(data){
						if(data.result == "1"){
							$.alert('删除成功');
							window.close();
						}
					}
				});
		    }
		});
	});
})


function bindApply(applyno){
	$.ajax({ 
		url: basePath() + 'business/getapplyinfo.do',
		data: {"applyno": applyno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		var jsonApply = data.datas.apply;
	    		var jsonBusiness = data.datas.business;
	    		var jsonMaterial = data.datas.material;
	    		var jsonShip = data.datas.ship;
	    		var jsonCoordinate = data.datas.coordinate;
	    		var jsonDevice = data.datas.device;


	    		applyid = jsonApply.applyid;
	    		
	    		bindApplyForm(jsonApply);
	    		
	    		//绑定业务资料
	    		bindBusinessForm(jsonBusiness);
	    		
	    		//绑定附件材料
	    		bindMaterialListForm(jsonMaterial);	    

	    		//绑定证书
	    		bindCertificate(jsonBusiness["recordcertificatelist"]);
	    		try{
		    		//绑定船舶数据
		    		if(undefined != jsonShip){
			    		if($('#shipname').length > 0){
				    		bindShipForm(jsonShip[0]);
//				    		var src;
//							if(jsonShip[0].verifyresult > 0)
//								src="../img/jiaoyan1.png";
//							else if(jsonShip[0].verifyresult == 0)
//								src="../img/jiaoyan2.png";
//							else
//								src="../img/jiaoyan3.png"
//							$("#shipcheckinfo").html('<img src="'+src+'" alt="" style="width:20px;height:20px;" data-toggle="modal" data-target="#modalCheck" onclick="getVerify(\''+jsonShip[0].shipidnumber+'\')" title="点击查看详情">');
							
			    		}
			    		else{
				    		if(jsonShip != ''){
				    			for(var i=0; i<jsonShip.length; i++){
				    				var data = jsonShip[i];
				    				bindShipInfoList(data);
				    			}
				    		}
			    		}
		    		}
	
		    		//绑定坐标
		    		if(jsonCoordinate != ''){
		    			for(var i=0; i<jsonCoordinate.length; i++){
		    				var data = jsonCoordinate[i];
		    				bindCoordinateInfoList(data);
		    			}
		    		}
		    		//绑定设备
		    		if(jsonDevice != ''){
		    			for(var i=0; i<jsonDevice.length; i++){
		    				var data = jsonDevice[i];
		    				bindDeviceInfoList(data);
		    			}
		    		}
	    		}catch (e) {}

	    		//查询文书
	    		getBookByApplyid(applyid);
	    		
//	    		if (itemno == '10001'){
//	    			//绑定证书
//	    			bindCertificate(jsonBusiness["recordcertificatelist"]);
//	    		}
	    	}
      	}
	});
}

function bindApplyForm(jsonApply){
	
	for(var d in jsonApply){//遍历json对象的每个key/value对,p为key
		if(d == 'applytime'){
			$('#' + d).html(formatDate(jsonApply[d], 'yyyy-mm-dd hh:mi'));
		}
		else if(d == 'nodename'){
        	if(jsonApply[d].indexOf('办结')>=0 || jsonApply[d].indexOf('不') >= 0){
        		if(jsonApply[d].indexOf('不') >= 0)
        			$('#' + d).html('<span style="color:red;font-weight: bold;">'+ jsonApply[d] +'</span>');
        		else
        			$('#' + d).html('<span style="color:green;font-weight: bold;">'+ jsonApply[d] +'</span>');
        		

//        		//如果是水上水下业务，在审批通过后，可对这个业务单进行变更（新业务新流程）
//        		if(itemno == '1002'){
//        			$('#change').show();
//    				$('#change').attr('href', 'edit.html?applyno=' + applyno + '&itemno=' + itemno + '&change=1');
//        		}
        	}
			else if(jsonApply[d].indexOf('补正') >= 0){
				$('#' + d).html('<span style="color:red;font-weight: bold;">' + jsonApply[d] + '</span>');
				$('#correction').show();

				if(itemno == '10001'){
					$('#correction').attr('href', 'recordEdit.html?applyno=' + applyno + '&itemno=' + itemno);
				} else {
					$('#correction').attr('href', 'correction.html?applyno=' + applyno + '&itemno=' + itemno);
				}
			}
			else if(jsonApply[d].indexOf('申报') >= 0){
				$('#' + d).html('<span style="color:red;font-weight: bold;">未提交</span>');
				$('#edit').show();
				$('#delete').show();
				if(itemno == '10001'){
					$('#edit').attr('href', 'recordEdit.html?applyno=' + applyno + '&itemno=' + itemno);
				} else {
					$('#edit').attr('href', 'edit.html?applyno=' + applyno + '&itemno=' + itemno);
				}
			}
        	else if(jsonApply[d].indexOf('受理') >= 0)
        		$('#' + d).html('<span style="color:blue; font-weight: bold;">待受理</span>');
			else{
				$('#' + d).html('<span style="color:blue;font-weight: bold;">已受理</span>');
			}
		}
		else{
			$('#' + d).html(jsonApply[d] == '' ? '/' : jsonApply[d]);
		}
	}
}

function bindBusinessForm(jsonBusiness){
	for ( var d in jsonBusiness) {// 遍历json对象的每个key/value对,p为key
		if (d == 'workbegintime' || d == 'workendtime'
				|| d == 'executionbegintime' || d == 'executionendtime'
				|| d == 'worktime' || d == 'workstarttime' || d == 'destinationporttime'
				|| d == 'ensurebegintime' || d == 'ensureendtime' || d == 'rescuetime'
			    || d == 'delaydate' || d == 'eventtime' || d == 'syscreated' || d == 'builddate') {
			$('#' + d).html(formatDate(jsonBusiness[d], 'yyyy-mm-dd'));
		} else if (d == 'waterwayname' || d == 'navigationmarkname') {
			$('#' + d).html(jsonBusiness[d] == '' ? '' : jsonBusiness[d] + ',');
		} else {
			if(itemno == '10003' && (d == "mobilephone" || d == "contactaddr")){
				$('#b' + d).html(jsonBusiness[d] == '' ? '/' : jsonBusiness[d]);
			}
			else	
			$('#' + d).html(jsonBusiness[d] == '' ? '/' : jsonBusiness[d]);
		}
	}
	
//	if (jsonBusiness['oldapplyno'] != '' && undefined != jsonBusiness['oldapplyno']) {
//		$('.change').show();
//		$('#itemname').html($('#itemname').html() + '（变更）');
//	}
}

function bindMaterialListForm(jsonMaterial){
	for(var i = 0; i < jsonMaterial.length; i++){
		var ismustsubmit = jsonMaterial[i]['ismustsubmit'];
		var ismustsubmitStr = "";
		var must = false;
		if(ismustsubmit == 1){
			ismustsubmitStr = '<span style="color:red;">*</span>';
			must = true;
		}
		var index = jsonMaterial[i]['serialnumber'];
		var quantity = jsonMaterial[i]['quantity'];
		var materialname = jsonMaterial[i]['materialname'];
		var fileid="";
		var fileurl = jsonMaterial[i]['fileurl'];
		
		var trStr = '<tr>																													'+
					'	<td><span name="serialnumber">'+ index +'</span></td>																'+
					'	<td style="text-align: left;"><span name="materialname">'+ materialname + '</span>' + ismustsubmitStr +'</td>		'+
					'	<td>'+ quantity +'</td>																								'+
					'	<td id="filename_'+ index +'">																						'+
					'		'+ fileurl +'																									'+
					'	</td>																												'+
					'</tr>';
		
		$('#' + tableID).find('tbody').append(trStr);
	}
}

function bindShipForm(jsonShip){
	for(var d in jsonShip){
		$('#' + d).html('<button type="button" style="padding:0px;" class="btn btn-link" onclick="showShipInfo(' + JSON.stringify(jsonShip).replace(/\"/g,"'") + ');">'+jsonShip[d]+'</button>');
	}
}

function showShipInfo(jsonShip){
	for(var j in jsonShip){
		if($('[name="' + j + '"]').length > 0){
			$('[name="' + j + '"]').val(jsonShip[j]);
		}
	}
	$('#modalShip').modal('show');
}

var total = 0;

function getBookByApplyid(applyid){
	$.ajax({ 
		url: basePath() + 'business/getamanuensis.do',
		data: {"applyid": applyid},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		var bookData = data.datas;

	    		for(var i = 0; i < bookData.length; i++){
	    			var ahtml = '<a target="_blank" href="/gahCSP/business/getamanuensisbyid.do?amanuensisid='+ bookData[i].amanuensisid +'"><button type="button" class="btn btn-link">'+ bookData[i].amanuensisname +'</button></a>'; 
	    			$('#book').append(ahtml);
	    		}
	    	}else{
	    		if(total<3){
	    			total++;
	    			setTimeout(getBookByApplyid, 3000,applyid);
	    		}
	    	}
      	}
	});
}

function bindNextNode(nodeno){
	$.ajax({ 
		url: basePath() + 'flow/getnextnodes.do',
		data: {"nodecode": nodeno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
			if(data.result == 1){
				var datas = data.datas;
				for(var i = 0; i < datas.length; i++){
					var nextnodecode = datas[i].nextnodecode;
					var nextnodename = datas[i].nextnodename;

					var controlhtml = '<input type="radio" value="'+ nextnodecode +'" text="'+ nextnodename +'"  name="nextnode" />';
					$("#nextnode").append(
							" <li>"
								+ controlhtml
								+ nextnodename
							+ "</li>");
				}
					    		

	    	    $("input[type=radio][name=nextnode]").bind("change", function() {

//					$('#opinion').val($(this).attr('text'));
		    		
					// 先清空控件数据
					$('#' + selectID).empty(); 
					
					var nextnodecode = $(this).attr('value');
					nextnodecode1 = nextnodecode;

					$.ajax({ 
						url: basePath() + 'flow/getuserbynodecode.do',
						data: {"nodecode": nextnodecode, "itemno": itemno, "orgcode": orgcode},
						dataType: "json",
				        contentType: "application/json",
						success: function(data){
					    	if(data.result == 1){

								for (var i = 0; i < data.datas.length; i++) {
									var value = data.datas[i].userid;
									var text = data.datas[i].username;
									
									var option = $("<option>").val(value).text(text).attr('data', JSON.stringify(data.datas[i])); 
									$('#' + selectID).append(option); 
								}
								
								var options = $('#' + selectID).find("option");
								options.first().attr("selected", true);
					    	}
				      	}
					});
				});
			}
      	}
	});
}

var tableID = 'material';
function bindMaterial(materialList){
	
    	
	for(var i = 0; i < materialList.length; i++){
		var ismustsubmit = materialList[i]['ismustsubmit'];
		var ismustsubmitStr = "";
		var must = false;
		if(ismustsubmit == 1){
			ismustsubmitStr = '<span style="color:red;">*</span>';
			must = true;
		}
		var index = materialList[i]['serialnumber'];
		var quantity = materialList[i]['quantity'];
		var materialname = materialList[i]['materialname'];
		var fileid="";
		var fileurl = materialList[i]['fileurl'];
		
		var trStr = '<tr>																													'+
					'	<td><span name="serialnumber">'+ index +'</span></td>																'+
					'	<td style="text-align: left;"><span name="materialname">'+ materialname + '</span>' + ismustsubmitStr +'</td>		'+
					'	<td>'+ quantity +'</td>																								'+
					'	<td id="filename_'+ index +'">																						'+
					'		'+ fileurl +'																									'+
					'	</td>																												'+
					'</tr>';
		
		$('#' + tableID).find('tbody').append(trStr);
	}
}

function save(){
	var users = []
	$('#' + selectID).find("option:selected").each(function(){
		users.push(jQuery.parseJSON($(this).attr('data')));
	})

	var businessid = applyid;
	var nodecode = nodeno;
	var opinion = $('#opinion').val();
	
	var formdata = {};
	formdata['businessid'] = businessid;
	formdata['nodecode'] = nodecode;
	formdata['opinion'] = opinion;
	formdata['nextnodecode'] = nextnodecode1;
	
	var params = {};
	params['auditopinion'] = formdata;
	params['users'] = users;
	
	if(!check(formdata, users))
		return true;
	
	
	$.ajax({ 
		method: 'post',
		url: basePath() + 'flow/auditopinion.do',
		data: JSON.stringify(params),
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
				window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.success,{
					onOk:function(v){
			    		parent.refreshData();		//刷新数据
					}
				});	
	    	} 
	    	else{
	    		window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.error);
	    	}
      	}
	});
}


function check(formdata, users){	
	var result = true;
	var strMsg = "";
	
	if(formdata['nextnodecode'] == '')	
		strMsg += '请选择下一步<br />';

	if(formdata['opinion'] == '')	
		strMsg += '请输入意见<br />';
	
//	if(users.length == 0)
//		strMsg += '请选择用户<br />';
	
	
	if(strMsg != ""){
    	window.wxc.xcConfirm(strMsg, window.wxc.xcConfirm.typeEnum.warning);
    	result = false;
	}
	
	return result;
}

function bindCertificate(recordcertificatelist){
	if(recordcertificatelist == null || recordcertificatelist == "")
		return ;
	
	for(var i=0;i<recordcertificatelist.length;i++){
		var effectivedate = formatDate(recordcertificatelist[i]["effectivedate"], 'yyyy-mm-dd') == '' ? '长期有效' : formatDate(recordcertificatelist[i]["effectivedate"], 'yyyy-mm-dd');
		var certificatetypename = recordcertificatelist[i]["certificatetypename"] == '' ? recordcertificatelist[i]["certificatetype"] : recordcertificatelist[i]["certificatetypename"];
		var html='	<tr>'+
		  '		<td>'+
		  certificatetypename +
		  '		</td>'+
		  '		<td>'+
		  formatDate(recordcertificatelist[i]["issuedate"], 'yyyy-mm-dd')	+
		  '		</td>'+
		  '		<td>'+
		  effectivedate	+
		  '		</td>'+
		  '		<td id="filename'+ recordcertificatelist[i]["certificateid"]+'"></td>'+
		  '	</tr>';	
		$("#recordcertificate").find('tbody').append(html);
		
		for(var j=0;j<recordcertificatelist[i]["recordcertificatefile"].length;j++){
			var filestr='<span style="display:block;">'+recordcertificatelist[i]["recordcertificatefile"][j]["FILEURL"]+'</span>'
			$("#filename"+recordcertificatelist[i]["certificateid"]).append(filestr);
		}
	}
}

function getVerify(shipidnumber){
	console.log(shipidnumber);
	var param = {};
	param['shipidnumber']  = shipidnumber;
	param['applyid'] = applyid;
	console.log(param);
	$.ajax({ 
		method: 'post',
		url: basePath() + 'share/getverify.do',
		data: JSON.stringify(param),
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		checkInfo(data.datas.data)
	    	} 
	    	else{
	    		window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.error);
	    	}
      	}
	});
}

function checkInfo(data) {

	 $("tr[name = 'checkInfo']").remove();
	var certstr = "", img = "",fscstr = "";
	for(var i=0;i<data.length;i++){
		if(data[i].verifyresultcode == 0)
			img = '<img src="../img/jiaoyan2.png" alt="" style="width:20px;height:20px;">';
		else if(data[i].verifyresultcode == 1)
			img = '<img src="../img/jiaoyan1.png" alt="" style="width:20px;height:20px;">';
		else
			img = '<img src="../img/jiaoyan3.png" alt="" style="width:20px;height:20px;">';
		if(data[i].verifytypecode == "0101" || data[i].verifytypecode == "0102" || data[i].verifytypecode == "0104"){   //法定证书校验
			certstr += '<tr name="checkInfo">' + '	<td style="text-align: center">' + data[i].verifyname
			+ '</td>' + '	<td style="text-align: center">' + img + '</td>'
			+ '	<td style="text-align: center">' + data[i].verifyresultdesc + '</td>'
			+ '	<tr>';
		}else if(data[i].verifytypecode == "0105"){
			fscstr += '<tr name="checkInfo">' + '	<td style="text-align: center">' + data[i].verifyname
			+ '</td>' + '	<td style="text-align: center">' + img + '</td>'
			+ '	<td style="text-align: center">' + data[i].verifyresultdesc + '</td>'
			+ '	<tr>';
		}
	}
	$("#certShip").append(certstr); //法定证书校验
	$("#fsc").append(fscstr);
}

